package com.baihui.crm.util;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;

import com.baihui.crm.BaihuiSession;
import com.baihui.taobao.authorize.TaoBaoSessionInfo;

/**
 * Created by Kevin. User: HSZM1106-0312 Date: 12-1-16 Time: 下午10:15
 */
public class BaihuiOptUtil {

	public static String insertRecord(BaihuiSession session,
			TaoBaoSessionInfo taobaosession, String type, String xmlDataString)
			throws Exception {
		if (session == null)
			return null;
		try {
			// ----------------------------Fetch Ticket ----------------------
			String token = session.getToken();
//			String apikey = session.getApiKey();
			String newFormat = "1";

			String targetURL = "https://crm.baihui.com/crm/private/xml/" + type
					+ "/insertRecords";
			String paramname = "content";

			PostMethod post = new UTF8PostMethod(targetURL);
			post.setParameter("authtoken", token);
			post.setParameter("scope", "crmapi");
			post.setParameter("newFormat", newFormat);
			post.setParameter("xmlData", xmlDataString);
			post.setParameter("wfTrigger", "true");

			HttpClient httpclient = new HttpClient();
			PrintWriter myout = null;

			// Execute http request
			try {
				long t1 = System.currentTimeMillis();
				int result = httpclient.executeMethod(post);

				// writing the response to a file
				myout = new PrintWriter(new File("response.xml"));
//				myout.print(post.getResponseBodyAsString());

				// ------------Get response as a string ----------
				return InputStreamToString(post
						.getResponseBodyAsStream());
			} catch (Exception e) {
				e.printStackTrace();
				throw e;
			} finally {
				myout.close();
				post.releaseConnection();
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
	}

	public static String selectRecord(BaihuiSession session, String type,
			Date date) throws Exception {
		if (session == null || "".equals(type))
			return null;
		try {
			// ----------------------------Fetch Ticket ----------------------
			String token = session.getToken();
//			String apikey = session.getApiKey();
			String newFormat = "1";
			String getDateURL = "https://crm.baihui.com/crm/private/xml/"
					+ type + "/getMyRecords";

			SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			PostMethod getdatepost = new PostMethod(getDateURL);
//			getdatepost.setParameter("ticket", ticket);
//			getdatepost.setParameter("apikey", apikey);
			getdatepost.setParameter("scope", "crmapi");
			getdatepost.setParameter("authtoken", token);
			getdatepost.setParameter("newFormat", newFormat);
			getdatepost.setParameter("fromIndex", "1");
			getdatepost.setParameter("toIndex", "100");
			getdatepost.setParameter("lastModifiedTime", f.format(date));
			if ("Products".equals(type)) {
				getdatepost.setParameter("selectColumns",
						"Products(PRODUCTID,Product Code)");
			} else if ("Contacts".equals(type)) {
				getdatepost.setParameter("selectColumns",
						"Contacts(CONTACTID,Last Name)");
			} else if ("SalesOrders".equals(type)) {
				// getdatepost.setParameter("selectColumns",
				// "SalesOrders(SALESORDERID,CONTACTID)");
			}
			// ------------Get response as a string ----------

			HttpClient httpclient = new HttpClient();
			PrintWriter myout = null;

			// Execute http request
			try {
				int result = httpclient.executeMethod(getdatepost);
				// writing the response to a file
				myout = new PrintWriter(new File("response.xml"));
				// myout.print(getdatepost.getResponseBodyAsString());

				// ------------Get response as a string ----------
				// System.out.println("getResponseBodyAsString =====" +
				// getdatepost.getResponseBodyAsString());
				return InputStreamToString(getdatepost
						.getResponseBodyAsStream());
			} catch (Exception e) {
				e.printStackTrace();
				throw e;
			} finally {
				myout.close();
				getdatepost.releaseConnection();
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
	}

	public static String InputStreamToString(InputStream is) throws IOException {

		StringBuffer out = new StringBuffer();
		InputStreamReader inread = new InputStreamReader(is, "utf-8");
		char[] b = new char[4096];
		for (int n; (n = inread.read(b)) != -1;) {
			out.append(new String(b, 0, n));
		}
		return out.toString();

	}

	public static String updateRecord(BaihuiSession session, String type,
			String xmlDataString, String id) throws Exception {
		if (session == null)
			return null;
		try {
			// ----------------------------Fetch Ticket ----------------------
			String token = session.getToken();
//			String apikey = session.getApiKey();
			String newFormat = "1";

			String targetURL = "https://crm.baihui.com/crm/private/xml/" + type
					+ "/updateRecords";

			PostMethod post = new UTF8PostMethod(targetURL);
			post.setParameter("authtoken", token);
//			post.setParameter("apikey", apikey);
			post.setParameter("scope", "crmapi");
			post.setParameter("newFormat", newFormat);
			post.setParameter("id", id);
			post.setParameter("xmlData", xmlDataString);
			post.setParameter("wfTrigger", "true");

			HttpClient httpclient = new HttpClient();
			PrintWriter myout = null;

			// Execute http request
			try {
				long t1 = System.currentTimeMillis();
				int result = httpclient.executeMethod(post);

				// writing the response to a file
				myout = new PrintWriter(new File("response.xml"));
				myout.print(post.getResponseBodyAsString());

				// ------------Get response as a string ----------
				return post.getResponseBodyAsString();
			} catch (Exception e) {
				e.printStackTrace();
				throw e;
			} finally {
				myout.close();
				post.releaseConnection();
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
	}

	public static String deleteRecord(BaihuiSession session, String type,
			String id) throws Exception {
		if (session == null)
			return null;
		try {
			// ----------------------------Fetch Ticket ----------------------
			String token = session.getToken();
//			String apikey = session.getApiKey();

			String targetURL = "https://crm.baihui.com/crm/private/xml/" + type
					+ "/deleteRecords";

			PostMethod post = new UTF8PostMethod(targetURL);
			post.setParameter("authtoken", token);
//			post.setParameter("apikey", apikey);
			post.setParameter("scope", "crmapi");
			post.setParameter("id", id);
			post.setParameter("wfTrigger", "true");

			HttpClient httpclient = new HttpClient();
			PrintWriter myout = null;

			// Execute http request
			try {
				long t1 = System.currentTimeMillis();
				int result = httpclient.executeMethod(post);

				// writing the response to a file
				myout = new PrintWriter(new File("response.xml"));
				myout.print(post.getResponseBodyAsString());

				// ------------Get response as a string ----------
				return post.getResponseBodyAsString();
			} catch (Exception e) {
				e.printStackTrace();
				throw e;
			} finally {
				myout.close();
				post.releaseConnection();
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
	}

	public static class UTF8PostMethod extends PostMethod {
		public UTF8PostMethod(String url) {
			super(url);
		}

		@Override
		public String getRequestCharSet() {
			return "UTF-8";
		}
	}
}
